package tcln.gxtx.client.utils.store;

import java.util.LinkedHashSet;
import java.util.Set;

import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.store.Record;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.widget.grid.GridView;

/**
 * Default implementation for a {@link RecordUpdater} which updates directly to the {@link Record} of a modified model.
 * 
 * @param <M>
 *            model data type.
 * @author Truong Chau Lien Ngoc (lienngoc@gmail.com)
 */
public class DefaultRecordUpdater<M extends ModelData> implements RecordUpdater<M> {
    protected Set<M> modifiedModels = new LinkedHashSet<M>();
    protected Store<M> ownerStore;
    protected GridView ownerGridView;

    protected DefaultRecordUpdater() {
        // to hide
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setGridView(GridView gridView) {
        this.ownerGridView = gridView;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setStore(Store<M> store) {
        this.ownerStore = store;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void commitChanges(boolean silent) {
        for (M m : modifiedModels) {
            Record record = ownerStore.getRecord(m);
            record.commit(silent);
        }

        modifiedModels.clear();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateRecord(M modifiedModel, String property, Object newValue) {
        Record record = ownerStore.getRecord(modifiedModel);
        record.set(property, newValue);
        modifiedModels.add(modifiedModel);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void finishUpdating() {
        // by default, does nothing because everything was done in 'updateRecord'.
    }
}